<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';

interface CustomerForm {
  id?: string;
  customerName: string;
  customerType: string;
  contactPhone: string;
  contactPerson: string;
  contactEmail: string;
  address: string;
  creditLimit: number;
  usedCredit: number;
  settlementCycle: string;
  status: number;
  remark: string;
}

const props = defineProps<{
  visible: boolean;
  customerData?: CustomerForm | null;
  isEdit?: boolean;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
  'confirm': [data: CustomerForm];
}>();

// 表单数据
const formData = reactive<CustomerForm>({
  customerName: '',
  customerType: 'enterprise',
  contactPhone: '',
  contactPerson: '',
  contactEmail: '',
  address: '',
  creditLimit: 0,
  usedCredit: 0,
  settlementCycle: 'monthly',
  status: 1,
  remark: ''
});

// 表单引用
const formRef = ref();

// 客户类型选项
const customerTypeOptions = [
  { value: 'enterprise', label: '企业客户' },
  { value: 'individual', label: '个人客户' },
  { value: 'government', label: '政府机构' }
];

// 状态选项
const statusOptions = [
  { value: 1, label: '正常' },
  { value: 0, label: '停用' }
];

// 结算周期选项
const settlementCycleOptions = [
  { value: 'weekly', label: '周结' },
  { value: 'monthly', label: '月结' },
  { value: 'quarterly', label: '季结' },
  { value: 'cash', label: '现结' }
];

// 表单验证规则
const rules = {
  customerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  customerType: [
    { required: true, message: '请选择客户类型', trigger: 'change' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactEmail: [
    { pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ],
  creditLimit: [
    { required: true, message: '请输入信用额度', trigger: 'blur' },
    { type: 'number', min: 0, message: '信用额度不能小于0', trigger: 'blur' }
  ]
};

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 重置表单
    resetForm();
    // 如果是编辑模式，填充数据
    if (props.isEdit && props.customerData) {
      Object.assign(formData, props.customerData);
    }
  }
});

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    customerName: '',
    customerType: 'enterprise',
    contactPhone: '',
    contactPerson: '',
    contactEmail: '',
    address: '',
    creditLimit: 0,
    usedCredit: 0,
    settlementCycle: 'monthly',
    status: 1,
    remark: ''
  });
  formRef.value?.clearValidate();
};

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false);
};

// 确认提交
const handleConfirm = async () => {
  try {
    await formRef.value?.validate();
    emit('confirm', { ...formData });
    handleClose();
    ElMessage.success(props.isEdit ? '编辑成功' : '新增成功');
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};
</script>

<template>
  <el-dialog
    :model-value="visible"
    :title="isEdit ? '编辑客户' : '新增客户'"
    width="600px"
    @update:model-value="handleClose"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="formData.customerName" placeholder="请输入客户名称" />
      </el-form-item>
      
      <el-form-item label="客户类型" prop="customerType">
        <el-select v-model="formData.customerType" placeholder="请选择客户类型" style="width: 100%">
          <el-option
            v-for="item in customerTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="联系人" prop="contactPerson">
        <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
      </el-form-item>
      
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
      </el-form-item>
      
      <el-form-item label="联系邮箱" prop="contactEmail">
        <el-input v-model="formData.contactEmail" placeholder="请输入联系邮箱" />
      </el-form-item>
      
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="formData.address"
          type="textarea"
          :rows="3"
          placeholder="请输入地址"
        />
      </el-form-item>
      
      <el-form-item label="信用额度" prop="creditLimit">
        <el-input-number
          v-model="formData.creditLimit"
          :min="0"
          :precision="2"
          style="width: 100%"
          placeholder="请输入信用额度"
        />
      </el-form-item>
      
      <el-form-item label="已用额度" prop="usedCredit">
        <el-input-number
          v-model="formData.usedCredit"
          :min="0"
          :precision="2"
          style="width: 100%"
          placeholder="请输入已用额度"
          :disabled="!isEdit"
        />
      </el-form-item>
      
      <el-form-item label="结算周期" prop="settlementCycle">
        <el-select v-model="formData.settlementCycle" placeholder="请选择结算周期" style="width: 100%">
          <el-option
            v-for="item in settlementCycleOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          {{ isEdit ? '保存' : '确定' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>